document.addEventListener('DOMContentLoaded', async function () {
    const questionList = document.getElementById('questionList');
    const searchInput = document.getElementById('searchInput');
    const statusFilter = document.getElementById('statusFilter');
    const questionModal = document.getElementById('questionModal');
    const answerForm = document.getElementById('answerForm');
    const answerResult = document.getElementById('answerResult');
    const userReply = document.getElementById('userReply');
    const addQuestionBtn = document.getElementById('addQuestionBtn');
    const customModal = document.getElementById('customQuestionModal');
    const closeCustomModal = document.getElementById('closeCustomModal');
    const customForm = document.getElementById('customQuestionForm');
    const loading = document.getElementById('loading'); // 获取加载动画元素

    // 防抖计时器
    let debounceTimer;

    // 打开自定义题模态窗
    addQuestionBtn.addEventListener('click', () => {
        customModal.classList.remove('hidden');
        customForm.reset(); // 清空表单
    });

    // 关闭模态窗
    closeCustomModal.addEventListener('click', () => {
        customModal.classList.add('hidden');
    });

    // 提交自定义题表单
    customForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const quesDesc = document.getElementById('customQuesDesc').value.trim();
        const exReply = document.getElementById('customExReply').value.trim();

        // 表单验证
        if (!quesDesc || !exReply) {
            Swal.fire({
                icon: 'warning',
                title: '请填写完整',
                text: '问题描述和示例答案均为必填项',
                background: '#fff',
                color: '#606266'
            });
            return;
        }

        // 显示加载动画
        loading.classList.remove('hidden');

        // 发送保存请求
        try {
            const response = await fetch('/quesUser/insertQuesUser', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    // 若需要Token认证，添加以下行
                    // 'Authorization': `Bearer ${localStorage.getItem('token')}`
                },
                body: JSON.stringify({
                    quesDesc,
                    exReply,
                    // 可选：默认状态设为未回答（0）
                    quesStatus: 0
                })
            });

            const data = await response.json();
            if (data.code === 200) {
                Swal.fire({
                    icon: 'success',
                    title: '保存成功',
                    text: '题目已添加到题库',
                    showConfirmButton: false,
                    timer: 1500,
                    background: '#f0f9eb',
                    iconColor: '#52c41a',
                    color: '#606266'
                });
                customModal.classList.add('hidden');
                // 刷新问题列表
                fetchQuestions();
            } else if (data.code === 401) {
                // 未登录处理
                window.location.href = '/view/login.html';
            } else {
                Swal.fire({
                    icon: 'error',
                    title: '保存失败',
                    text: data.message || '请重试',
                    background: '#fef0f0',
                    iconColor: '#ff4d4f',
                    color: '#606266'
                });
            }
        } catch (error) {
            console.error('保存题目失败:', error);
            Swal.fire({
                icon: 'error',
                title: '网络错误',
                text: '无法连接到服务器',
                background: '#fef0f0',
                iconColor: '#ff4d4f',
                color: '#606266'
            });
        } finally {
            // 隐藏加载动画
            loading.classList.add('hidden');
        }
    });

    // 定义搜索函数
    async function fetchQuestions(quesDesc = '', quesStatus = '') {
        // 显示加载动画
        loading.classList.remove('hidden');

        try {
            // 发送带参数的请求
            const response = await fetch('/quesUser/quesUserList', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    quesDesc,
                    quesStatus: quesStatus !== '' ? quesStatus : null
                })
            });

            const data = await response.json();

            if (data.code === 200) {
                questionList.innerHTML = ``;
                const isEmpty = !data.data || data.data.length === 0;

                if (isEmpty) {
                    questionList.innerHTML = `<!-- 空状态提示 -->
        <div class="empty-state">
            <div class="w-20 h-20 rounded-full bg-primary/10 flex items-center justify-center mb-4">
                <i class="fa fa-question-circle text-primary text-3xl"></i>
            </div>
            <h3 class="text-lg font-medium text-neutral-700 mb-2">暂无答题记录</h3>
            <p class="mb-6">点击下方按钮让小助手生成你的专属面试题(输入口令：我的专属面试题)</p>
            <button onclick="window.location.href='/view/chicken.html'" class="btn-primary">
                <i class="fa fa-magic mr-2"></i> 生成专属面试题
            </button>
        </div>`
                    const emptyState = questionList.querySelector('.empty-state');
                    emptyState.style.display = 'flex'; // 显示空状态
                } else {
                    // 渲染问题列表
                    data.data.forEach(question => {
                        const card = document.createElement('div');
                        card.className = 'question-card';

                        // 根据问题状态设置不同的样式
                        let statusClass, statusText, statusIcon;
                        switch (question.quesStatus) {
                            case 0: // 未回答
                                statusClass = 'bg-warning/10 text-warning';
                                statusText = '未回答';
                                statusIcon = 'fa-clock-o';
                                break;
                            case 1: // 已回答
                                statusClass = 'bg-secondary/10 text-secondary';
                                statusText = '已回答';
                                statusIcon = 'fa-check-circle-o';
                                break;
                            default:
                                statusClass = 'bg-neutral-200 text-neutral-600';
                                statusText = '未知状态';
                                statusIcon = 'fa-question-circle-o';
                        }

                        card.innerHTML = `
                                <div class="flex justify-between items-start">
                                    <div class="flex-1">
                                        <h3 class="font-medium text-neutral-800 mb-2 cursor-pointer hover:text-primary transition-colors" onclick="showQuestionDetail(${question.quesUserId})">
                                            ${question.quesDesc}
                                        </h3>
                                    </div>
                                    <span class="status-badge ${statusClass}">
                                        <i class="fa ${statusIcon} mr-1"></i> ${statusText}
                                    </span>
                                </div>
                                <div class="flex justify-between items-center mt-4 pt-4 border-t border-neutral-100">
                                    <div class="text-sm text-neutral-500">
                                        <i class="fa fa-calendar-o mr-1"></i> 添加于 ${question.createTime || '未知时间'}
                                    </div>
                                    <div class="flex space-x-2">
                                        <button class="text-neutral-500 hover:text-danger transition-colors delete-btn" data-id="${question.quesUserId}">
                                            <i class="fa fa-trash-o"></i> 删除
                                        </button>
                                    </div>
                                </div>
                            `;

                        questionList.appendChild(card);
                    });

                    // 绑定删除按钮事件
                    bindDeleteEvents();
                }
            } else if (data.code === 401) {
                // 未授权处理
                await Swal.fire({
                    icon: 'warning',
                    title: '登录状态失效',
                    text: '请重新登录以访问该页面',
                    confirmButtonText: '前往登录',
                    background: '#fef4f4',
                    iconColor: '#FF4444',
                    color: '#606266',
                });
                window.location.href = '/view/login.html';
                return;
            } else {
                // 错误处理
                questionList.innerHTML = `
                        <div class="empty-state">
                            <div class="w-20 h-20 rounded-full bg-danger/10 flex items-center justify-center mb-4">
                                <i class="fa fa-exclamation-triangle text-danger text-3xl"></i>
                            </div>
                            <h3 class="text-lg font-medium text-neutral-700 mb-2">${data.message || '查询失败'}</h3>
                            <button onclick="location.reload()" class="btn-primary">重试</button>
                        </div>
                    `;
            }
        } catch (error) {
            console.error('搜索请求出错:', error);
            questionList.innerHTML = `
                    <div class="empty-state">
                        <div class="w-20 h-20 rounded-full bg-neutral-200 flex items-center justify-center mb-4">
                            <i class="fa fa-wifi text-neutral-500 text-3xl"></i>
                        </div>
                        <p>网络连接错误，请重试</p>
                        <button onclick="location.reload()" class="btn-primary">重试</button>
                    </div>
                `;
        } finally {
            // 隐藏加载动画
            loading.classList.add('hidden');
        }
    }

    // 绑定删除按钮事件
    function bindDeleteEvents() {
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', async function () {
                const quesUserId = this.getAttribute('data-id');
                const result = await Swal.fire({
                    title: '确认删除',
                    text: '你确定要删除这个问题吗？',
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonText: '删除',
                    cancelButtonText: '取消',
                    reverseButtons: true,
                    background: '#fff',
                    color: '#606266',
                    confirmButtonColor: '#ff4d4f',
                    cancelButtonColor: '#909399'
                });

                if (result.isConfirmed) {
                    // 显示加载动画
                    loading.classList.remove('hidden');

                    try {
                        const response = await fetch(`/quesUser/deleteById/${quesUserId}`, {
                            method: 'GET'
                        });

                        const data = await response.json();
                        if (data.code === 200) {
                            Swal.fire({
                                icon: 'success',
                                title: '删除成功',
                                text: '问题已被成功删除',
                                showConfirmButton: false,
                                timer: 1500,
                                background: '#f0f9eb',
                                iconColor: '#52c41a',
                                color: '#606266'
                            });
                            // 重新加载问题列表
                            fetchQuestions(searchInput.value.trim(), statusFilter.value);
                        } else if (data.code === 401) {
                            // 未授权处理
                            await Swal.fire({
                                icon: 'warning',
                                title: '登录状态失效',
                                text: '请重新登录以访问该页面',
                                confirmButtonText: '前往登录',
                                background: '#fef4f4',
                                iconColor: '#FF4444',
                                color: '#606266',
                            });
                            window.location.href = '/view/login.html';
                            return;
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: '删除失败',
                                text: data.message || '删除操作失败',
                                background: '#fef0f0',
                                iconColor: '#ff4d4f',
                                color: '#606266'
                            });
                        }
                    } catch (error) {
                        console.error('删除请求出错:', error);
                        Swal.fire({
                            icon: 'error',
                            title: '网络错误',
                            text: '无法连接到服务器',
                            background: '#fef0f0',
                            iconColor: '#ff4d4f',
                            color: '#606266'
                        });
                    } finally {
                        // 隐藏加载动画
                        loading.classList.add('hidden');
                    }
                }
            });
        });
    }

    // 添加输入框回车搜索
    searchInput.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') {
            fetchQuestions(searchInput.value.trim(), statusFilter.value);
        }
    });

    // 添加状态筛选变化事件
    statusFilter.addEventListener('change', () => {
        fetchQuestions(searchInput.value.trim(), statusFilter.value);
    });

    // 添加搜索框输入防抖
    searchInput.addEventListener('input', (e) => {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(() => {
            fetchQuestions(e.target.value.trim(), statusFilter.value);
        }, 500); // 500ms延迟
    });

    // 关闭模态窗
    document.getElementById('closeModal').addEventListener('click', () => {
        questionModal.classList.add('hidden');
        answerForm.reset();
        answerResult.classList.add('hidden');
        answerForm.classList.remove('hidden');
    });

    // 提交回答
    answerForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const quesUserId = parseInt(document.getElementById('modalTitle').dataset.id);
        const userReplyValue = userReply.value.trim();

        if (!userReplyValue) {
            Swal.fire({
                icon: 'warning',
                title: '回答不能为空',
                text: '请输入你的回答内容',
                background: '#fff',
                color: '#606266'
            });
            return;
        }

        // 显示加载动画
        loading.classList.remove('hidden');

        // 禁用提交按钮
        const submitButton = answerForm.querySelector('button[type="submit"]');
        submitButton.disabled = true;

        try {
            const response = await fetch(`/ai/submitAnswer/${quesUserId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userReply: userReplyValue })
            });

            const data = await response.json();
            if (data.code === 200) {
                answerForm.classList.add('hidden');
                answerResult.classList.remove('hidden');
                document.getElementById('statusText').textContent = '当前状态：已回答';
                document.getElementById('statusText').className = 'mt-4 text-sm text-success';

                // 刷新问题列表
                setTimeout(() => {
                    fetchQuestions(searchInput.value.trim(), statusFilter.value);
                }, 1000);
            } else if (data.code === 401) {
                await Swal.fire({
                    icon: 'warning',
                    title: '登录状态失效',
                    text: '请重新登录以继续',
                    confirmButtonText: '前往登录',
                    background: '#fef4f4',
                    iconColor: '#FF4444',
                    color: '#606266',
                });
                window.location.href = '/view/login.html';
            } else {
                Swal.fire({
                    icon: 'error',
                    title: '提交失败',
                    text: data.message || '请重试',
                    background: '#fef0f0',
                    iconColor: '#ff4d4f',
                    color: '#606266'
                });
            }
        } catch (error) {
            console.error('提交回答失败:', error);
            Swal.fire({
                icon: 'error',
                title: '网络错误',
                text: '无法连接到服务器',
                background: '#fef0f0',
                iconColor: '#ff4d4f',
                color: '#606266'
            });
        } finally {
            // 隐藏加载动画
            loading.classList.add('hidden');
            // 启用提交按钮
            submitButton.disabled = false;
        }
    });

    // 初始加载
    fetchQuestions();
});

// 显示问题详情函数
function showQuestionDetail(quesUserId) {
    // 显示加载动画
    loading.classList.remove('hidden');

    fetch(`/quesUser/quesUserInfo/${quesUserId}`)
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                const question = data.data;
                // 新增：处理小助手建议
                const suggestionContent = document.getElementById('suggestionContent');
                const suggestionSection = document.getElementById('suggestionSection');

                if (question.suggestion) {
                    // 存在建议时显示区域并填充内容
                    suggestionSection.style.display = 'block';
                    suggestionContent.textContent = question.suggestion;
                } else {
                    // 无建议时隐藏区域
                    suggestionSection.style.display = 'none';
                }

                document.getElementById('modalTitle').textContent = question.quesDesc;
                document.getElementById('modalTitle').dataset.id = question.quesUserId;

                // 填充示例答案和得分
                document.getElementById('exReply').textContent = question.exReply;
                document.getElementById('point').textContent = question.point;

                // 设置状态显示
                const statusText = document.getElementById('statusText');

                // 获取用户回答显示区域
                const userReplyDisplay = document.getElementById('userReplyDisplay');
                const userReplyContent = document.getElementById('userReplyContent');

                if (question.quesStatus === 1) {
                    // 已回答状态
                    statusText.textContent = '当前状态：已回答';
                    statusText.className = 'mt-4 text-sm text-success';
                    document.getElementById('answerForm').classList.add('hidden');
                    document.getElementById('answerResult').classList.remove('hidden');

                    // 显示用户回答
                    userReplyDisplay.classList.remove('hidden');
                    userReplyContent.textContent = question.userReply || '（无回答内容）';

                    // 同时填充文本框（用于编辑）
                    document.getElementById('userReply').value = question.userReply || '';
                } else {
                    // 未回答状态
                    statusText.textContent = '当前状态：未回答';
                    statusText.className = 'mt-4 text-sm text-warning';
                    document.getElementById('answerForm').classList.remove('hidden');
                    document.getElementById('answerResult').classList.add('hidden');

                    // 隐藏用户回答区域
                    userReplyDisplay.classList.add('hidden');
                    document.getElementById('userReply').value = '';
                }

                // 显示模态窗
                document.getElementById('questionModal').classList.remove('hidden');
            } else if (data.code === 401) {
                Swal.fire('登录失效', '请重新登录', 'warning').then(() => {
                    window.location.href = '/view/login.html';
                });
            } else {
                Swal.fire('错误', data.message || '获取问题详情失败', 'error');
            }
        })
        .catch(error => {
            console.error('获取问题详情失败:', error);
            Swal.fire('网络错误', '请检查网络连接', 'error');
        })
        .finally(() => {
            // 隐藏加载动画
            loading.classList.add('hidden');
        });
}